package com.hsl.housaileibot001.ai.mcp;

import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.mcp.client.DefaultMcpClient;
import dev.langchain4j.mcp.client.transport.http.HttpMcpTransport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.Retryable;
import org.springframework.retry.support.RetryTemplate;

import java.time.Duration;

/**
 * @author liul
 * @date 2025/10/18 23:15
 */
// @Configuration
public class McpConfig {
    @Value("${bigmodel.api-key}")
    private String apiKey;

    @Bean
    @Retryable(value = {Exception.class}, maxAttempts = 3)
    public McpToolProvider mcpToolProvider() {
        try {
            // 和 mcp 服务建立连接
            HttpMcpTransport transport = new HttpMcpTransport.Builder()
                    .sseUrl("https://open.bigmodel.cn/api/mcp/web_search/sse?Authorization=" + apiKey)
                    .logRequests(true)
                    .logResponses(true)
                    .timeout(Duration.ofMinutes(5)) // 设置5分钟超时
                    .build();
            
            // 创建 mcp 客户端
            DefaultMcpClient mcpClient = new DefaultMcpClient.Builder()
                    .key("hsl")
                    .transport(transport)
                    .build();
            
            // 从 mcp 客户端获取工具
            McpToolProvider mcpToolProvider = new McpToolProvider.Builder()
                    .mcpClients(mcpClient)
                    // .filterToolNames("mcp_search")
                    .build();
            return mcpToolProvider;
        } catch (Exception e) {
            // 如果MCP连接失败，返回一个空的工具提供者
            System.err.println("MCP连接失败，将使用备用方案: " + e.getMessage());
            return new McpToolProvider.Builder().build();
        }
    }
}
